'use strict';

const BaseService = require('./base');
const modelName = 'Order';
const { Op } = require('sequelize');
const dayjs = require("dayjs");
function generateOrderNo() {
  const now = dayjs();
  // 生成格式：年月日时分秒+4位随机数
  return 'ON' + now.format('YYYYMMDDHHmmss') + Math.floor(Math.random() * 10000).toString().padStart(4, '0');
}

class RouterService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }

  async create(data) {
    delete data.id
    /**
     * address_id: this.addressData.id,
     *         type: this.data.productType,
     *         remark: this.buyerMessage,
     *         cartIds: this.data.data.split(','),
     *         total_amount: this.realAmount,
     *         discount_amount: this.discountAmount,
     *         pay_amount: this.payAmount,
     *         points: this.use_point ? this.maxUsePointFee * 100 : 0,
     *         member_user_id: this.userId,
     *         recipient_name: this.addressData.name,
     *         recipient_phone: this.addressData.phone,
     *         recipient_province: this.addressData.province,
     *         recipient_city: this.addressData.city,
     *         recipient_district: this.addressData.district,
     *         recipient_address: this.addressData.address
     */
    // 创建事务
    const transaction = await this.ctx.model.transaction();
    try {
      let order = null
      /**
       * 校验商品、用户、库存
       */
      let memberUser = await this.ctx.model.MemberUser.findByPk(data.member_user_id);
      if (!memberUser) {
        throw new Error('用户不存在');
      }
      let cartList = await this.ctx.model.Cart.findAll({
        where: {
          id: {
            [Op.in]: data.cartIds
          }
        },
        include: [
          {
            model: this.ctx.model.ProductItem,
            as: 'productItem',
          },
          {
            model: this.ctx.model.Product,
            as: 'product',
          }
        ],
      })
      if (cartList.length === 0) {
        throw new Error('购物车为空');
      }
      /**
       * 购物车删除
       */
      await this.ctx.model.Cart.destroy({
        where: {
          id: {
            [Op.in]: data.cartIds
          }
        },
        transaction
      })
      /**
       * 库存查询和扣减
       */
      for (let i = 0; i < cartList.length; i++) {
        let item = cartList[i];
        if (item.productItem.stock < item.quantity) {
          throw new Error('库存不足');
        } else {
          // 扣减库存
          await this.ctx.model.ProductItem.update({
            stock: item.productItem.stock - item.quantity
          }, {
            where: {
              id: item.productItem.id
            },
            transaction
          })
          // 增加商品销量
          await this.ctx.model.Product.update({
            sales: item.product.sales + item.quantity
          }, {
            where: {
              id: item.product.id
            },
            transaction
          })
          // 增加商品规格销量
          await this.ctx.model.ProductItem.update({
            sales: item.productItem.sales + item.quantity
          }, {
            where: {
              id: item.productItem.id
            },
            transaction
          })
        }
      }
      /**
       * 用户积分扣减
       */
      await this.ctx.model.MemberUser.update({
        points: memberUser.points - data.points
      }, {
        where: {
          id: memberUser.id
        },
        transaction
      })
      /**
       * 创建订单、子订单
       */
      const order_no = generateOrderNo()
      console.log({
        order_no,
        ...data,
        cartIds: undefined
      })
      order = await this.ctx.model.Order.create({
        order_no,
        ...data,
        cartIds: undefined
      }, { transaction });
      // 平均的积分抵扣
      let pointFee = 0;
      if (data.points > 0) {
        pointFee = Math.floor(data.points / cartList.length);
      }
      await this.ctx.model.OrderItem.bulkCreate(
        cartList.map(item => ({
          order_id: order.id,
          order_no,
          product_id: item.product_id,
          product_item_id: item.product_item_id,
          quantity: item.quantity,
          price: item.productItem.price,
          pay_amount: Math.floor(item.quantity * item.productItem.price - pointFee).toFixed(2),
          points: pointFee
        })),
        { transaction }
      )
      await transaction.commit();
      return order;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
}


module.exports = RouterService;
